package mipushdemo.xiaomi.com.diyitonghang.ui.fragment.home;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.daasuu.bl.BubbleLayout;
import com.daasuu.bl.BubblePopupHelper;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import mipushdemo.xiaomi.com.diyitonghang.R;
import mipushdemo.xiaomi.com.diyitonghang.api.ApiService;
import mipushdemo.xiaomi.com.diyitonghang.app.AppUrl;
import mipushdemo.xiaomi.com.diyitonghang.base.BaseFragment;
import mipushdemo.xiaomi.com.diyitonghang.data.bean.HomeDataBean;
import mipushdemo.xiaomi.com.diyitonghang.data.bean.NewsChannelData;
import mipushdemo.xiaomi.com.diyitonghang.data.bean.TabBean;
import mipushdemo.xiaomi.com.diyitonghang.presenter.contract.homecontract.IDataContract;
import mipushdemo.xiaomi.com.diyitonghang.presenter.impl.zixunimpl.DataPresenterImpl;
import mipushdemo.xiaomi.com.diyitonghang.ui.activity.MainActivity;
import mipushdemo.xiaomi.com.diyitonghang.ui.adapter.HomeRecyAdapter;
import mipushdemo.xiaomi.com.diyitonghang.ui.adapter.MyLinearLayoutManager;
import mipushdemo.xiaomi.com.diyitonghang.ui.fragment.HomeFragment;
import mipushdemo.xiaomi.com.diyitonghang.utils.RetrofitUtils;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class HomeSonFragment extends BaseFragment implements IDataContract.IDataView<IDataContract.IDataPresenter> {
    @BindView(R.id.homeSonRecyView)
    RecyclerView homeSonRecyView;
    Unbinder unbinder;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private TabBean bean;
    private IDataContract.IDataPresenter dataPresenter;
    private PopupWindow popupWindow;
    public static List<HomeDataBean.DataBean.NewListBean> mList = new ArrayList();
    private HomeRecyAdapter homeRecyAdapter;
    private String channelId;
    private PopupWindow deletePopup;
    private int times = 0;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bean = (TabBean) getArguments().getSerializable("bean");
        channelId = bean.getChannelId();

    }

//    private boolean isLazyLoaded;
//    private boolean isPrepared;

    @Override
    protected void init(View view) {
//        isPrepared = true;
        refreshAndLoadMore();
//        setUserVisibleHint(true);
        new DataPresenterImpl(this);
        lazyLoad();

        homeSonRecyView.setLayoutManager(new MyLinearLayoutManager(getContext()));
        homeSonRecyView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));

        homeRecyAdapter = new HomeRecyAdapter(mList);
        homeSonRecyView.setAdapter(homeRecyAdapter);
        homeRecyAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(getContext(), InfoActivity.class);
                intent.putExtra("newsId",mList.get(position).getNewsId());
                startActivity(intent);
            }
        });
        final BubbleLayout inflate = (BubbleLayout) LayoutInflater.from(getContext()).inflate(R.layout.delete_home_popup, null);
        deletePopup = BubblePopupHelper.create(getContext(), inflate);
        homeRecyAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                ImageView im = view.findViewById(R.id.iv_delete);
                inflate.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
                int mShowMorePopupWindowWidth = -view.getMeasuredWidth();
                int mShowMorePopupWindowHeight = -view.getMeasuredHeight();
//                int[] location = new int[2];
//                view.getLocationInWindow(location);
//                inflate.setArrowDirection(ArrowDirection.TOP);
//                deletePopup.showAtLocation(view, Gravity.NO_GRAVITY, location[0], view.getHeight() + location[1]);
                deletePopup.showAsDropDown(im, mShowMorePopupWindowWidth, mShowMorePopupWindowHeight);


            }
        });
    }

    @Override
    protected void loadData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_homeson;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void loading() {
        popupWindow = new PopupWindow((MainActivity)getActivity());
        View view = LayoutInflater.from(getContext()).inflate(R.layout.home_popup, null);
        popupWindow.setContentView(view);
        popupWindow.setHeight(200);
        popupWindow.setWidth(200);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(null);
//        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
    }

    @Override
    public void showData(HomeDataBean homeDataBean) {
        mList.clear();
        List<HomeDataBean.DataBean.NewListBean> newList = homeDataBean.getData().getNewList();
        mList.addAll(newList);
        homeRecyAdapter.notifyDataSetChanged();
        if(refreshLayout!=null){
            refreshLayout.finishRefresh();

        }
    }

    @Override
    public void completed() {
        popupWindow.dismiss();
    }

    @Override
    public void setPresenter(IDataContract.IDataPresenter iDataPresenter) {
        dataPresenter = iDataPresenter;
    }


//    @Override
//    public void setUserVisibleHint(boolean isVisibleToUser) {
//        if (isVisibleToUser && isPrepared && !isLazyLoaded) {
//            lazyLoad();
//            isLazyLoaded = true;
//        }
//    }


//    @Override
//    public void setUserVisibleHint(boolean isVisibleToUser) {
//        super.setUserVisibleHint(isVisibleToUser);
//        if(isVisibleToUser){
//            lazyLoad();
//        }
//    }

    private void lazyLoad() {
        dataPresenter.login(channelId, MainActivity.userId);
    }


    private void refreshAndLoadMore(){
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                lazyLoad();
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                loadMore();
            }
        });
    }


    private void loadMore(){
        ApiService apiService = RetrofitUtils.newInstance().netWorkRequest();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userId",MainActivity.userId);
            jsonObject.put("channelId",channelId);
            jsonObject.put("cursor",(times++)+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse(AppUrl.URL_HEADER), jsonObject.toString());
        Observable<HomeDataBean> observable = apiService.homeLoadMoreData(AppUrl.URL_HEADER, requestBody);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<HomeDataBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(HomeDataBean homeDataBean) {
                        List<HomeDataBean.DataBean.NewListBean> newList = homeDataBean.getData().getNewList();
                        mList.addAll(newList);
                        homeRecyAdapter.notifyDataSetChanged();
                        refreshLayout.finishLoadmore();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}


